package c.c.d.s.s.o.c.rs.configuration;

import c.c.d.s.s.o.c.rs.configuration.support.response.ResponseWrapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import org.springframework.security.web.csrf.MissingCsrfTokenException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义的 AccessDeniedHandler
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-05-08 17:48
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {

        if (accessDeniedException instanceof MissingCsrfTokenException) {
            ResponseWrapper.forbiddenResponse(response, "Require csrf-token.");
        }

        if (accessDeniedException instanceof InvalidCsrfTokenException) {
            ResponseWrapper.forbiddenResponse(response, "Invalid csrf-token.");
            return;
        }

        ResponseWrapper.forbiddenResponse(response, accessDeniedException.getMessage());
    }

}
